package com.jindi.jacococli.api.aop;

import com.jindi.jacococli.biz.utils.JSONUtils;
import com.jindidata.jindi.utils.common.ResultWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class WebResultWrapperAOP implements ResponseBodyAdvice<Object> {

    private static final List<String> IGNORE_URLS = new ArrayList<>();
    private static final String MANAGEMENT_PROMETHEUS_URL = "/management/prometheus";
    private static final String SWAGGER_RESOURCES = "swagger-resources";
    private static final String API_DOC = "api-docs";
    private static final String CHECK_ALIVE = "/checkAlive";

    static {
        IGNORE_URLS.add(MANAGEMENT_PROMETHEUS_URL);
        IGNORE_URLS.add(SWAGGER_RESOURCES);
        IGNORE_URLS.add(API_DOC);
        IGNORE_URLS.add(CHECK_ALIVE);
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> clazz, ServerHttpRequest request, ServerHttpResponse response) {
        String path = request.getURI().getPath();
        boolean flag = IGNORE_URLS.stream().anyMatch(path::contains);
        if (flag) {
            return body;
        }
        if (body instanceof ResultWrapper) {
            return body;
        } else if (body instanceof String) {
            return JSONUtils.toJSONString(ResultWrapper.builder().ok(body).build());
        }
        return ResultWrapper.builder().ok(body).build();
    }
}